package com.toune.movie.mvp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.toune.movie.R;
import com.toune.movie.base.AppConstant;
import com.toune.movie.base.BaseActivity;
import com.toune.movie.base.myUtil.MyUtil;
import com.toune.movie.mvp.adapter.AdapterSearch;
import com.toune.movie.mvp.adapter.AdapterVariety;
import com.toune.movie.mvp.contract.SearchContract;
import com.toune.movie.mvp.presenter.SearchPresenter;
import com.toune.movie.vo.SearchVo;
import com.toune.movie.vo.VarietyVo;
import com.vondear.rxtool.RxDataTool;
import com.vondear.rxtool.RxDeviceTool;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/5/16.
 */

public class SearchActivity extends BaseActivity<SearchPresenter> implements SearchContract.View {
    @BindView(R.id.mLreclView)
    RecyclerView mLreclView;
    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.search_btn)
    Button searchBtn;
    private List<SearchVo> allVarietyList = new ArrayList<>();
    private AdapterSearch adapterVariety;
    private String searchText = "";

    @Override // 实例化presenter
    public SearchPresenter initPresenter() {
        return new SearchPresenter();
    }

    @Override
    public void loadMore() {
    }

    @Override
    public void refreData() {
        mPresenter.getVos(searchText);
    }

    @Override
    public void init(Bundle savedInstanceState) {
        searchText = getIntent().getStringExtra("searchText");
        searchEt.setText(searchText);
        searchEt.setSelection(searchText.length());
        if (!RxDataTool.isEmpty(searchText)) {
            MyUtil.showProDialog(context);
            mPresenter.getVos(searchText);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_search;
    }

    @Override
    protected String getTitleStr() {
        return getResources().getString(R.string.search);
    }

    @Override
    protected void initEventAndData() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void useNightMode(boolean isNight) {

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            notifyAdapter();
            MyUtil.hidProDialog();
        }
    };

    private void notifyAdapter() {
        if (adapterVariety == null) {
            adapterVariety = new AdapterSearch(R.layout.adapter_search_list, allVarietyList);
            mLreclView.setLayoutManager(new LinearLayoutManager(context));
            mLreclView.setAdapter(adapterVariety);
            adapterVariety.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    int tag = 0;
                    switch (allVarietyList.get(position).getTag()) {
                        case "电影":
                            tag = 0;
                            break;
                        case "综艺":
                            tag = 2;
                            break;
                        case "电视剧":
                            tag = 1;
                            break;
                        case "动漫":
                            tag = 3;
                            break;
                    }
                    Intent intent = new Intent(context, VarietyDetailActivity.class);
                    intent.putExtra("url", allVarietyList.get(position).getDetailUrl());
                    intent.putExtra("title", allVarietyList.get(position).getTitle());
                    intent.putExtra("tag", tag);//0表示是电影，1表示电视剧，2表示综艺
                    intent.putExtra("imgUrl", allVarietyList.get(position).getImgURL());
                    startActivity(intent);
                }
            });
        } else {
            adapterVariety.notifyDataSetChanged();
        }
    }

    @Override
    public void setVos(List<SearchVo> voList) {
        if (!allVarietyList.containsAll(voList)) {
            allVarietyList.addAll(voList);
            handler.sendEmptyMessage(0);
        }
    }

    @OnClick(R.id.search_btn)
    public void onViewClicked() {
        search(searchEt.getText().toString());
    }

    private void search(String content) {
        AVQuery<AVObject> avQuery = new AVQuery<>(AppConstant.TAB_SEARCH);
        avQuery.whereMatches("context", content);
        avQuery.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list.size() == 0) {
                        insertDb();
                    }
                } else {
                    insertDb();
                }
            }
        });
        MyUtil.showProDialog(context);
        mPresenter.getVos(content);
    }

    private void insertDb() {
        //搜素历史存进数据库
        AVObject avObject = new AVObject(AppConstant.TAB_SEARCH);
        if (AVUser.getCurrentUser() != null) {
            avObject.put("userId", AVUser.getCurrentUser().getObjectId());
        }
        avObject.put("phoneId", RxDeviceTool.getUniqueSerialNumber());
        avObject.put("context", searchEt.getText().toString());
//        avObject.addUnique("context", searchEt.getText().toString());
        avObject.saveInBackground();
    }

}
